package com.shelpe.services.tenant.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shelpe.services.tenant.dao.CategoryMapper;
import com.shelpe.services.tenant.model.Category;
import com.shelpe.services.tenant.proxy.CategoryClient;
import com.shelpe.services.tenant.proxy.CategoryClient.CategoryDto;
import com.shelpe.services.tenant.proxy.CategoryClient.CategoryListRespone;
import com.shelpe.services.tenant.service.CategoryService;

@Service
public class CategoryServiceImpl implements CategoryService{

	private static final Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);
	
	@Autowired
	private CategoryClient catClient;
	
	@Autowired
	private CategoryMapper catMapper;

	
	@Override
	public List<Category> getCategoryFromProxy(Long userId, Integer type, String categoryIds){ 
		
		CategoryListRespone res = catClient.getCategory(userId, type, categoryIds);
		
		List<CategoryDto> categories = null;
		
		if(res != null && res.getRes() != null && res.getRes().getDataList() != null){
			
			categories = res.getRes().getDataList().getCategories();
		}else{
			if(res != null){
				logger.error("getCategoryFromProxy, something is wrong, response {}", res.getError());
			}
		}
		
		List<Category> result = new ArrayList<Category>();
		if(categories != null && categories.size() > 0){
			for(CategoryDto dto : categories){
				Category cat = new Category();
				cat.setCatId(dto.getCategoryID());
				cat.setCatName(dto.getName());
				cat.setCatLevel(dto.getLevel());
				cat.setCatPathId(dto.getCategoryIDs());
				cat.setParentCatId(dto.getParentID());
				cat.setCatPathName(dto.getName());
				
				result.add(cat);
			}
		}
		
		return result;
	}

	@Override
	public Category getCategoryById(Integer cid) {
		// TODO Auto-generated method stub
		return catMapper.selectByPrimaryKey(cid);
	}

	public int insertCategory(Category cat){
		
		return catMapper.insert(cat);
	}

}
